<?php

class Admin_Model_User extends Zend_Db_Table_Abstract {

    protected $_name = 'users';
    protected $_primary = 'uid';

    public function getUserByUsername($username) {
        $select = $this->select()
                ->where('userName = ?', $username, STRING)
                ->where('status = ?', 1);
        return $this->fetchRow($select);
    }

    public function getUserOne($id) {
        $select = $this->select()
                ->where('uid = ?', $id)
                ->where('status = ?', 1);
        return $this->fetchRow($select);
    }

    public function addUser($info) {
        $data = array(
            'userName' => $info['userName'],
            'password' => md5(md5($info['password']) . $this->_generateSalt()),
            'email' => $info['email'],
            'name' => $info['name'],
            'salt' => $this->_generateSalt(),
            'roleId' => $info['roleId'],
            'status' => $info['status'],
            'created' => $info['created'],
        );
        $id = $this->insert($data);

        return $id;
    }

    public function updateUser($id, $info) {
        $this->update($info, "uid=" . (int) $id);
    }

    public function deleteUser($uid) {
        $this->delete("uid = " . (int) $uid);
    }

    public function countItems() {
        $query = $this->select()
                ->from('users', 'count(uid) as total');
        $result = $this->fetchRow($query);
        return $result->total;
    }

    private function _generateSalt($length = 3) {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $string = '';
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, (strlen($characters) - 1))];
        }
        return $string;
    }

}